/**
  Szybkie operacje na listach postingowych
  wersja z rankingiem
*/
#include <stdio.h>
#include <math.h>
#include<Python.h>
#undef assert
#define assert(X) {if(!(X)){printf("assertion failed on line %d\n >>%s\n", __LINE__, #X);++*((int*)(NULL));}}

int** links;
int* len;
int* score;
int totalNumber;

int nextNode(int node){
    
    if( len[node] == 0 ){
        return rand() % totalNumber;
    }
    else{
        if(rand() % 1000 == 1)
            return rand() % totalNumber;
        else
            return links[node][ rand() % len[node] ];    
    }
}

static PyObject* putLinks(PyObject* self, PyObject* args)
{
    PyObject * o1;
    int number;
    if (!PyArg_ParseTuple(args, "Oi", &o1, &number) )
        return NULL;
    
    int len1 = (int) PyList_Size( o1 );
    links[number] = malloc(len1 * sizeof(int) );
    len[number] = len1;
    
    int i;
    for( i = 1 ; i < len1 ; i++)
    {
        links[number][i] = PyLong_AsLong( PyList_GET_ITEM(o1, i) );
    }
    
   return Py_BuildValue("i",  0 ) ;     
}

static PyObject* _init(PyObject* self, PyObject* args)
{
    int number;
    if (!PyArg_ParseTuple(args, "i", &number) );
        return NULL;    
        
    totalNumber = number;
    links = malloc( number * sizeof(int *) );
    len = malloc(number * sizeof(int) );
    score = malloc(number * sizeof(int) );
    int i;
    
    for(i = 0 ; i < number ; i++){
        len[i] = 0;
    }
    return Py_BuildValue("i",  0 );
}

static PyObject* iter(PyObject* self, PyObject* args)
{
    int number;
    PyObject * o1;    
    if (!PyArg_ParseTuple(args, "Oi", &o1,&number) );
        return NULL;    
    
    int i;
    for(i = 0 ; i < totalNumber; i++){
        score[i] = 0;
    }
    int node = 0;
    while(number-- > 0){
        score[node] ++;
        node = nextNode(node);     
    }
    
    for( i = 0 ; i < totalNumber; i++ )
    {
        PyList_SetItem(o1, (Py_ssize_t) i, PyLong_FromLong( score[i] ) );
    }
    
    return o1;
}

static PyMethodDef HelloMethods[] =
{
     {"putLinks", putLinks, METH_VARARGS, " "},
     {"iter", iter, METH_VARARGS, " "},
     {"init", _init, METH_VARARGS, " "},     
     {NULL, NULL, 0, NULL}
};
 
PyMODINIT_FUNC inititeruj(void)
{
     (void) Py_InitModule("iteruj", HelloMethods);
}
